//
//  EventViewController.m
//  WindRunner
//
//  Created by leeqb on 9/12/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "EventViewController.h"
#import "ActivityEditViewController.h"
#import "ActivityDetailViewController.h"
#import "AppDelegate.h"
#import "BaseTabBarController.h"
#import "GuidePageView.h"
#import "LoginViewController.h"
#import "ActivityAnnotation.h"

#define KEY_EVENT_TERMS_AGREE   @"EventTermsAgree"

@interface EventViewController ()
{
    BOOL                    _isSecret;
    BOOL                    _isActivityListLoaded;
    NSInteger               _currRow;
    NSInteger               _currPageCount;
    
    NSMutableArray          *_activityList;
    NSDictionary            *_currActivityData;
    NSMutableArray          *_annotations;
}
@end

@implementation EventViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        self.navigationItem.hidesBackButton = YES;
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 首次进入，显示引导页
    [GuidePageView showGuidePage];
    
    if(![[NSUserDefaults standardUserDefaults] boolForKey:KEY_EVENT_TERMS_AGREE]) {
        NSArray *arr = [[NSBundle mainBundle] loadNibNamed:@"TermsController" owner:self options:nil];
        UIViewController *termsController = arr[0];
        [self presentViewController:termsController animated:YES completion:^{
        }];
    }
    
    _activityList = [[NSMutableArray alloc] init];
    _annotations = [[NSMutableArray alloc] init];
    
    _activityTable.hidden = YES;
    _activityTable.custDelegate = self;
    _activityTable.showRefreshControl = YES;
    
    UIImage *itemIconImage = [UIImage imageNamed:@"evt_bar_left_icon2.png"];
    CGRect rect = _mapBarButton.frame;
    rect.size.width = itemIconImage.size.width / 2.5;
    rect.size.height = itemIconImage.size.height / 2.5;
    _mapBarButton.frame = rect;
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    if(![AuthHelper isLogin]) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Security" bundle:nil];
        LoginViewController *loginVC = [storyboard instantiateInitialViewController];
        loginVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:loginVC animated:NO];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    self.navigationItem.title = LocalStringEvent(@"NAV_TITLE_HOME");
    self.tabBarController.tabBar.hidden = NO;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(locationUpdate) name:KEY_LOCATION_UPDATE object:nil];
    
    [LocationHelper refreshLocation];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KEY_LOCATION_UPDATE object:nil];
}

// 服务条款界面点击同意
- (IBAction)agreeClicked:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:KEY_EVENT_TERMS_AGREE];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }];
}

// 服务条款界面点击不同意
- (IBAction)disagreeClicked:(UIButton *)sender {
    [FMToast showMessage:@"If you do not agree,do not continue to use the software!Otherwise,as agreed to these terms"];
}


// 私密活动状态切换
- (void)onSecretChange:(BOOL)isSecret
{
    _isSecret = isSecret;
    if(_activityTable.hidden) {
        [self loadActivityList:1 pageNum:1];
    } else {
        [_activityList removeAllObjects];
        [self loadActivityList:2 pageNum:1];
    }
}

// 加载活动列表，queryType为1表示加载地图，为2表示加载活动列表
- (void)loadActivityList:(NSInteger)queryType pageNum:(NSInteger)pageNum
{
    if([AuthHelper getCurrentUser]) {
        NSDictionary *requestData = @{@"userid":[AuthHelper getCurrentUser][@"id"],
                                      @"locationX":[NSString stringWithFormat:@"%lf", CURR_COORDINATE_X],
                                      @"locationY":[NSString stringWithFormat:@"%lf", CURR_COORDINATE_Y],
                                      @"pageindex":[NSNumber numberWithInteger:pageNum],
                                      @"pagesize":LIST_PAGE_SIZE,
                                      @"secret":[NSNumber numberWithInteger:_isSecret]};
        FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                                 interface:@"activelist"
                                                                    params:requestData];
        [FMNetwork request:requestObj showMask:NO success:^(NSDictionary *data) {
            if(queryType == 1) {
                // 添加标注前，先删除已有的标注
                [_mapView removeAnnotations:_annotations];
                [_annotations removeAllObjects];
                NSDictionary *record = data[@"record"];
                if(record && ![record isEqual:[NSNull null]]) {
                    NSArray *listData = record[@"data"];
                    [self addAnnotations:listData];
                }
            } else if(queryType == 2) {
                if(pageNum <= 1) {
                    [_activityList removeAllObjects];
                }
                NSArray *tempArr = data[@"record"][@"data"];
                _currPageCount = tempArr.count;
                [_activityList addObjectsFromArray:tempArr];
                [self.activityTable reloadData];
                [_activityTable tableDataRefreshed:([tempArr count]==0)];
                _isActivityListLoaded = YES;
            }
        } falied:^(NSError *error) {
            [_activityTable tableDataRefreshed:NO];
        }];
    } else {
        [_activityTable tableDataRefreshed:NO];
    }
}

- (void)addAnnotations:(NSArray *)listData
{
    if(listData && ![listData isEqual:[NSNull null]]) {
        for(NSDictionary *rowData in listData) {
            NSString *locX = [NSString formatString:rowData[@"locationX"]];
            NSString *locY = [NSString formatString:rowData[@"locationY"]];
            if(![locX isEqualToString:@""] && ![locY isEqualToString:@""]) {
                CLLocationCoordinate2D coor;
                coor.longitude = [locX doubleValue];
                coor.latitude = [locY doubleValue];
                ActivityAnnotation *actAnnotation = [[ActivityAnnotation alloc] init];
                actAnnotation.title1 = [NSString formatString:rowData[@"title"]];
                actAnnotation.subtitle1 = [NSString formatString:rowData[@"location"]];
                actAnnotation.customData = rowData;
                actAnnotation.coordinate = coor;
                [_annotations addObject:actAnnotation];
            }
        }
        [_mapView addAnnotations:_annotations];
    }
}

// 私密活动密码提示框
- (void)showSecretAlert
{
    UIAlertView *secretAlert = [[UIAlertView alloc] initWithTitle:LocalStringCommon(@"ALERT_TITLE")
                                                          message:LocalStringEvent(@"SECRET_ALERT_TITLE")
                                                         delegate:self
                                                cancelButtonTitle:LocalStringCommon(@"ALERT_CANCEL")
                                                otherButtonTitles:LocalStringCommon(@"ALERT_OK"), nil];
    secretAlert.alertViewStyle = UIAlertViewStyleSecureTextInput;
    
    // 私密活动密码输入框
    UITextField * txt = [[UITextField alloc] init];
    txt.backgroundColor = [UIColor whiteColor];
    txt.frame = CGRectMake(secretAlert.center.x+65,secretAlert.center.y+48, 150,23);
    [secretAlert addSubview:txt];
    
    [secretAlert show];
}

- (void)removeActivity:(NSDictionary *)data
{
    [_activityList removeObject:data];
    [_activityTable reloadData];
}

- (void)locationUpdate
{
    CLLocationCoordinate2D theCoordinate;
    theCoordinate.latitude = CURR_COORDINATE_Y;
    theCoordinate.longitude = CURR_COORDINATE_X;
    
    MKCoordinateSpan theSpan;
    theSpan.latitudeDelta = 0.1;
    theSpan.longitudeDelta = 0.1;
    
    MKCoordinateRegion theRegion;
    theRegion.center = theCoordinate;
    theRegion.span = theSpan;
    
    [_mapView setRegion:theRegion animated:YES];
    [self loadActivityList:1 pageNum:1];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    self.tabBarController.tabBar.hidden = YES;
    
    if([[segue identifier] isEqualToString:@"segActivityDetail"]) {
        ActivityDetailViewController *vc = (ActivityDetailViewController *)[segue destinationViewController];
        vc.eventContoller = self;
        if(_currActivityData) {
            vc.data = _currActivityData;
        } else {
            vc.data = _activityList[_currRow];
        }
    }
}

// 点击导航栏左边的按钮，切换图标
- (IBAction)mapClick:(UIButton *)sender {
    UIImage *itemIconImage = [UIImage imageNamed:@"evt_bar_left_icon2.png"];
    
    if(_activityTable.hidden) {
        if(!_isActivityListLoaded) {
            [self loadActivityList:2 pageNum:1];
        }
        
        _mapBarButton.contentEdgeInsets = UIEdgeInsetsMake(0, -2, 0, 2);
        itemIconImage = [UIImage imageNamed:@"active_icon.png"];
        _activityTable.hidden = NO;
        _mapView.hidden = YES;
    } else {
        _mapBarButton.contentEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 0);
        _activityTable.hidden = YES;
        _mapView.hidden = NO;
    }
    
    CGRect rect = _mapBarButton.frame;
    rect.size.width = itemIconImage.size.width / 2.5;
    rect.size.height = itemIconImage.size.height / 2.5;
    _mapBarButton.frame = rect;
    [_mapBarButton setImage:itemIconImage forState:UIControlStateNormal];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _activityList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ActivityCell" forIndexPath:indexPath];
        
    UIActivityIndicatorView *indicatorView = (UIActivityIndicatorView *)[cell viewWithTag:2];
    [indicatorView startAnimating];
    NSDictionary *rowData = _activityList[indexPath.row];
    if(rowData) {
        UILabel *titleLabel = (UILabel *)[cell viewWithTag:3];
        UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
        
        NSString *strTitle = rowData[@"title"];
        if(strTitle && ![strTitle isEqualToString:@""]) {
            titleLabel.text = rowData[@"title"];
        }
        imageView.image = [UIImage getDefaultImageInSize:imageView.frame.size];
        
        NSString *imageUrl = rowData[@"imgurl"];
        if(imageUrl && ![imageUrl isEqual:[NSNull null]] && ![imageUrl isEqualToString:@""]) {
            imageUrl = [NSString stringWithFormat:@"%@%@", IMAGE_URL_PREFIX, imageUrl];
            FMDownloadImage *downloader = [[FMDownloadImage alloc] initWithTarget:imageView];
            [downloader downLoadImageWithURL:imageUrl imagetype:@"ActivityListImages"];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    _currRow = indexPath.row;
    _currActivityData = _activityList[_currRow];
    
    // 私密活动弹出密码提示框
    if([_currActivityData[@"secret"] boolValue]) {
        [self showSecretAlert];
    } else {
        [self performSegueWithIdentifier:@"segActivityDetail" sender:self];
    }
}

#pragma mark CustTableViewDelegate
- (void)refreshTableData:(UITableView *)tableview
{
    [self loadActivityList:2 pageNum:1];
}

- (void)loadNextPage:(UITableView *)tableview nextPageNum:(NSInteger)nextPageNum
{
    [self loadActivityList:2 pageNum:nextPageNum];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row==(_activityList.count-1) && _currPageCount==[LIST_PAGE_SIZE integerValue]) {
        [_activityTable loadNextPage];
    }
}

#pragma mark EMChatManagerDelegate methods
// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    UIApplication *application = [UIApplication sharedApplication];
    AppDelegate *appDelegate = (AppDelegate *)application.delegate;
    BaseTabBarController *tabController = appDelegate.tabBar;
    UITabBarItem *tabMessage = [tabController.tabBar.items objectAtIndex:0];
    if(unreadCount > 0) {
        tabMessage.badgeValue = [NSString stringWithFormat:@"%ld", (long)unreadCount];
        [application setApplicationIconBadgeNumber:unreadCount];
    } else {
        tabMessage.badgeValue = nil;
        [application setApplicationIconBadgeNumber:0];
    }
}

#pragma mark MKMapViewDelegate
- (MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id<MKAnnotation>)annotation
{
    // 当前坐标不做处理
    if([annotation isKindOfClass:[MKUserLocation class]]) {
        return nil;
    }
    
    NSString *pinIdentifier = @"ActivityAnnotation";
    MKPinAnnotationView *pinView = (MKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:pinIdentifier];
    if(!pinView) {
        pinView = [[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pinIdentifier];
        pinView.pinColor = MKPinAnnotationColorGreen;
        pinView.canShowCallout = YES;
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
        pinView.rightCalloutAccessoryView = button;
    }
    
    return pinView;
}

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control
{
    ActivityAnnotation *actAnnotation = (ActivityAnnotation *)view.annotation;
    _currActivityData = actAnnotation.customData;
    // 点击地图上的标注，检查是否私密活动，如果是私密活动则弹出密码输入框，不是私密活动直接进入详情界面
    if([_currActivityData[@"secret"] boolValue]) {
        [self showSecretAlert];
    } else {
        [self performSegueWithIdentifier:@"segActivityDetail" sender:self];
    }
}

#pragma mark 私密活动密码提示框点击【确定】按钮
- (BOOL)alertViewShouldEnableFirstOtherButton:(UIAlertView *)alertView
{
    // 只有在输入密码后【确定】按钮才可以点击
    UITextField *txt = [alertView textFieldAtIndex:0];
    NSString *inputPassword = [NSString formatString:txt.text];
    if([inputPassword isEqualToString:@""]) {
        return NO;
    } else {
        return YES;
    }
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1) {
        UITextField *txt = [alertView textFieldAtIndex:0];
        NSString *inputPassword = [NSString formatString:txt.text];
        NSString *activityPassword = [NSString formatString:_currActivityData[@"password"]];
        // 判断输入的密码与活动密码是否一致
        if([inputPassword isEqualToString:activityPassword]) {
            [self performSegueWithIdentifier:@"segActivityDetail" sender:self];
        } else {
            [FMToast showMessage:LocalStringEvent(@"SECRET_PASS_ERROR")];
        }
    }
}

@end
